package foliotracker.GUI;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.UUID;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import foliotracker.Portfolio;
import foliotracker.Stock;
import foliotracker.views.IFolioTrackerView;
import foliotracker.views.IPortfolioView;

public class PortfolioView extends JPanel implements IPortfolioView
{
	private static final long serialVersionUID = 1L;
	private Portfolio folio;
	private JTable table;
	
	public PortfolioView(final IFolioTrackerView mainView, final Portfolio folio)
	{
		super(new GridLayout(1, 0));
		
		this.folio = folio;
		
	    table = new JTable(new PortfolioTableModel(folio));
	    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
	    table.setAutoCreateRowSorter(true);
	    
	    table.addMouseListener(new MouseListener()
	    {
			@Override
			public void mouseClicked(MouseEvent arg0)
			{
				if (arg0.getClickCount() == 2)
				{
					//double click
					mainView.openStockView(folio.getStocks().get(table.getSelectedRow()));
				}
			}

			@Override
			public void mouseEntered(MouseEvent arg0)
			{
			}

			@Override
			public void mouseExited(MouseEvent arg0)
			{
			}

			@Override
			public void mousePressed(MouseEvent arg0)
			{
			}

			@Override
			public void mouseReleased(MouseEvent arg0)
			{
			}
	    	
	    });
	    
	    //Create the scroll pane and add the table to it.
	    JScrollPane scrollPane = new JScrollPane(table);

	    //Add the scroll pane to this panel.
	    add(scrollPane);
	    scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
	}


	@Override
	public Portfolio getPortfolio()
	{
		return folio;
	}

	@Override
	public UUID getSelectedStockID()
	{
		if (table.getSelectedRow() == -1)
			return null;
		
		Stock stock = folio.getStocks().get(table.getSelectedRow());
		return stock.getId();
	}
	
}
